package com.threeti.mecool.core.domain.model.basicdata.biz;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.threeti.mecool.framework.util.Lists;

public abstract class MeCoolAdminDivisionAreaRegistry {
  private static Map<String, List<String>> customAreaRegistry = new LinkedHashMap<String, List<String>>();
  
  private static Map<String, String[]> customAreaNameCodeRegistry = new HashMap<String, String[]>();
  
  public static final String EAST_AREA_CODE = "1"; 
  public static final String SOUTH_AREA_CODE = "2";
  public static final String WEST_AREA_CODE = "3";
  public static final String NORTH_AREA_CODE = "4";
  
  public static final String[] EAST_AREA_NAME_CODE = {"东区", EAST_AREA_CODE};
  public static final String[] SOUTH_AREA_NAME_CODE = {"南区", SOUTH_AREA_CODE};
  public static final String[] WEST_AREA_NAME_CODE = {"西区", WEST_AREA_CODE};
  public static final String[] NORTH_AREA_NAME_CODE = {"北区", NORTH_AREA_CODE};
  
  static {
    customAreaNameCodeRegistry.put(EAST_AREA_CODE, EAST_AREA_NAME_CODE);
    customAreaNameCodeRegistry.put(SOUTH_AREA_CODE, SOUTH_AREA_NAME_CODE);
    customAreaNameCodeRegistry.put(WEST_AREA_CODE, WEST_AREA_NAME_CODE);
    customAreaNameCodeRegistry.put(NORTH_AREA_CODE, NORTH_AREA_NAME_CODE);
    
    Resource rs = new ClassPathResource("mecool_adminarea.properties");
    
    Properties prop = new Properties();
    try {
      prop.load(rs.getInputStream());
      Set<Entry<Object, Object>> provincesAndAreas = prop.entrySet();
      for (Entry<Object, Object> provinceAndArea : provincesAndAreas) {
        String areaCode = (String)provinceAndArea.getValue();
        String provinceAdCode = (String)provinceAndArea.getKey();
        
        List<String> areas;
        if ((areas = customAreaRegistry.get(areaCode)) != null) {
          areas.add(provinceAdCode);
        } else {
          areas = Lists.newArrayList(provinceAdCode);
          customAreaRegistry.put(areaCode, areas);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    
    
  }
  
  public static Map<String, List<String>> customAreaRegistry() {
    return customAreaRegistry;
  }
  
  public static Map<String, String[]> customAreaNameCodeRegistry() {
    return customAreaNameCodeRegistry;
  }

  public static boolean isAreaNameSpecial(String areaName) {
    return 
        "市辖区".equals(areaName) || "县".equals(areaName) || "(市)".equals(areaName);
  }
}
